import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserInfoDto } from '../model/dto/user-info.dto';
import { User } from '../user/entities/user.entity';
import { RecordActionLogDto } from './dto/record-action-log.dto';
import { UserActionLogDto } from './dto/user-action-log.dto';
import { ActionLog, EActionLogTypeEnum } from './entities/action-log.entity';

@Injectable()
export class ActionLogsService {
  constructor(
    @InjectRepository(ActionLog)
    private actionLogRepository: Repository<ActionLog>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  async add(recordActionLogDto: RecordActionLogDto, user: UserInfoDto) {
    const exitUser = await this.userRepository.findOneBy({ id: user?.id });
    if (!exitUser) {
      throw new Error('缺少用户id');
    }

    const updateData = await this.actionLogRepository.findOne({
      where: {
        userId: user.id,
        type: recordActionLogDto.type,
        name: recordActionLogDto.name,
        description: recordActionLogDto.description,
        content: recordActionLogDto.content,
        relevancyId: recordActionLogDto.relevancyId,
      },
    });

    if (updateData) {
      updateData.useCount++;
      await this.actionLogRepository.save(updateData);
      return { message: '修改记录' };
    }

    const data = this.actionLogRepository.create({
      ...recordActionLogDto,
      userId: user.id,
    });

    await this.actionLogRepository.save(data);

    return { message: '新增记录' };
  }

  async findAll(user: UserInfoDto) {
    const exitUser = await this.userRepository.findOneBy({ id: user?.id });
    if (!exitUser) {
      throw new Error('缺少用户id');
    }

    const componentList = await this.actionLogRepository.find({
      where: {
        userId: user.id,
      },
      order: {
        useCount: 'DESC',
        updateAt: 'DESC',
        createAt: 'DESC',
      },
    });

    return componentList;

    // const templateList = (await this.queryDetail(
    //   user,
    //   'template',
    //   'Template',
    // )) as UserActionLogDto[];
    // const kitList = (await this.queryDetail(
    //   user,
    //   'kit',
    //   'Kit',
    // )) as UserActionLogDto[];
    // const componentList = (await this.actionLogRepository.find({
    //   where: {
    //     type: EActionLogTypeEnum.Component,
    //     userId: user.id,
    //   },
    // })) as unknown as UserActionLogDto[];

    // return [...templateList, ...kitList, ...componentList];
  }

  async queryDetail(user: UserInfoDto, property: string, type: string) {
    return this.actionLogRepository
      .createQueryBuilder('actionLog')
      .leftJoin(
        property,
        'C',
        'actionLog.relevancyId = C.id AND actionLog.type = :type',
        { type: type },
      )
      .where('actionLog.userId = :userId', { userId: user.id })
      .andWhere('actionLog.type = :type', { type: type })
      .select([
        'actionLog.*',
        `C.name AS name`,
        `C.description AS description`,
        // `${property}.name`,
        // `${property}.description`,
      ])
      .getRawMany();
  }

  // findOne(id: number) {
  //   return `This action returns a #${id} actionLog`;
  // }

  // update(id: number, updateActionLogDto: UpdateActionLogDto) {
  //   return `This action updates a #${id} actionLog`;
  // }

  // remove(id: number) {
  //   return `This action removes a #${id} actionLog`;
  // }
}
